package com.manlitech.cloudboot.oauth.config.filter;

import com.alibaba.fastjson.JSONObject;
import com.manlitech.cloudboot.common.enums.ResultEnums;
import com.manlitech.cloudboot.common.utils.Result;
import com.manlitech.cloudboot.common.utils.ResultUtil;
import com.manlitech.cloudboot.oauth.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 账号密码登录和校验过滤器
 * @author shensg
 * @date 2021/7/7 18:06
 */
@Slf4j
public class JwtAuthenticateFilter extends UsernamePasswordAuthenticationFilter {

    Logger logger = LoggerFactory.getLogger(JwtAuthenticateFilter.class);

    private  final AuthenticationManager authenticationManager;

    public JwtAuthenticateFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    //用户发起请求，拦截，获取用户名密码表单
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        String  username=request.getParameter("username");
        String  password=request.getParameter("password");
        UsernamePasswordAuthenticationToken uToken=new UsernamePasswordAuthenticationToken(username,password);
        //用户认证
        return  this.authenticationManager.authenticate(uToken);
    }

    @Override
    protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
        return super.requiresAuthentication(request, response);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        Result result = ResultUtil.error(ResultEnums.NO_LOGIN.getCode(),ResultEnums.NO_LOGIN.getMsg());
        logger.warn(JSONObject.toJSONString(result));
        out.write(JSONObject.toJSONString(result));
    }

    //校验证成功，将token 信息返回给用户
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        User user =(User) authResult.getPrincipal();
        List<String> roles = user.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());
        String token = JwtTokenUtil.build(user.getUsername(), user.getPassword() ,roles);
        response.setHeader("Authorization",token);
        response.setContentType("application/json;charset=utf-8");

        PrintWriter out = response.getWriter();
        Result result = ResultUtil.success(user.getUsername());
        logger.info(JSONObject.toJSONString(result));
        out.write(JSONObject.toJSONString(result));

    }
}
